import java.util.*;

/**
 * @Author 12629
 * @Description：
 */
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }
    //这个二叉树的根节点
    //public TreeNode root;
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        //E.right = H;
        return A;
    }

    public TreeNode createTree2() {
        TreeNode A = new TreeNode('1');
        TreeNode B = new TreeNode('2');
        TreeNode C = new TreeNode('3');
        TreeNode D = new TreeNode('4');

        A.left = B;
        A.right = C;
        B.left = D;
        return A;
    }

    // 前序遍历
    void preOrder(TreeNode root) {
        if(root == null) return;
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }
    //前序遍历 OJ
    /*public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) return ret;
        ret.add(root.val);
        List<Integer> leftTree = preorderTraversal(root.left);
        ret.addAll(leftTree);

        List<Integer> rightTree = preorderTraversal(root.right);
        ret.addAll(rightTree);

        return ret;
    }*/



    // 中序遍历
    void inOrder(TreeNode root) {
        if(root == null) return;
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    /*public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) return ret;
        List<Integer> leftTree = inorderTraversal(root.left);
        ret.addAll(leftTree);

        ret.add(root.val);

        List<Integer> rightTree = inorderTraversal(root.right);
        ret.addAll(rightTree);
        return ret;
    }*/

    // 后序遍历
    void postOrder(TreeNode root) {
        if(root == null) return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }

    /*public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) return ret;
        List<Integer> leftTree = postorderTraversal(root.left);
        ret.addAll(leftTree);


        List<Integer> rightTree = postorderTraversal(root.right);
        ret.addAll(rightTree);

        ret.add(root.val);

        return ret;
    }*/

    // 子问题思路  获取树中节点的个数
    int size(TreeNode root) {
        if(root == null) return 0;
        return size(root.left) + size(root.right) + 1;
    }
    //遍历思路：只要遍历到了节点 就nodeSize ++
    public static int nodeSize;
    void size2(TreeNode root) {
        if(root == null) return;
        nodeSize++;
        size2(root.left);
        size2(root.right);
    }

    //子问题 获取叶子节点的个数
    int getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left)
                + getLeafNodeCount(root.right);
    }

    //遍历思路
    public static int leafSize;
    void getLeafNodeCount2(TreeNode root) {
        if(root == null) return;
        if(root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
    }

    // 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root,int k) {
        if(root == null) return 0;
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k-1) +
                getKLevelNodeCount(root.right,k-1);
    }

    // 获取二叉树的高度  时间复杂度：O(N)
    int getHeight(TreeNode root) {
        if(root == null) return 0;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return (leftHeight > rightHeight ?
                leftHeight+1 : rightHeight+1);
    }

    //重复计算
    int getHeight1(TreeNode root) {
        if(root == null) return 0;
        return (getHeight1(root.left) > getHeight1(root.right) ?
                getHeight1(root.left)+1 : getHeight1(root.right)+1);
    }

    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val) {
        if(root == null) return null;
        if(root.val == val) {
            return root;
        }
        TreeNode ret1 = find(root.left,val);
        if(ret1 != null) {
            return ret1;
        }
        TreeNode ret2 = find(root.right,val);
        if(ret2 != null) {
            return ret2;
        }
        return null;
    }

    /**
     * 时间复杂度：
     * O(min(n,m))
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //这里只是判断的 一个为空 一个不为空的情况 。
        // 你没有判断 两个都是空 和 两个都不是空的情况
        if(p == null && q != null || p != null && q == null) {
            return false;
        }

        if(p == null && q == null) {
            return true;
        }

        if(p.val != q.val) {
            return false;
        }

        //p != null && q != null && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
    //时间复杂度：O(n*m) 假设root这棵树的节点个数n   subRoot节点个数是m
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) return false;

        if(isSameTree(root,subRoot)) return true;

        if(isSubtree(root.left,subRoot)) return true;

        if(isSubtree(root.right,subRoot)) return true;

        return false;
    }

    //时间复杂度：O(N^2)
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.abs(leftHeight-rightHeight) <= 1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }

    //这个题 是字节考过的原题 O(n)
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int leftTree = maxDepth(root.left);
        int rightTree = maxDepth(root.right);

        if(leftTree >= 0 && rightTree >= 0 && Math.abs(leftTree - rightTree) <= 1) {
            return Math.max(leftTree,rightTree) + 1;
        }else {
            return -1;
        }
    }

    public boolean isBalanced2(TreeNode root) {
        if(root == null) return true;
        return maxDepth(root) >= 0;
    }


    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }

        return isSymmetricChild(root.left,root.right);
    }

    private boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree == null && rightTree != null || leftTree != null && rightTree == null)   {
            return false;
        }

        if(leftTree == null && rightTree == null) {
            return true;
        }

        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }

    //层序遍历
    void levelOrder(TreeNode root) {
        if(root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }

    /**
     * 层序遍历
     * @param root
     * @return
     */
   /* public List<List<Integer>> levelOrder2(TreeNode root) {
        //还是依赖于队列
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();//4
            List<Integer> row = new ArrayList<>();
            while (size > 0) {
                TreeNode cur = queue.poll();
                size--;//0
                //System.out.print(cur.val + " ");
                row.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(row);
        }
        return ret;
    }*/

    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if(root == null) return true;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }

        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if(cur != null) {
                //不是满二叉树
                return false;
            }else {
                queue.poll();
            }
        }
        return true;
    }

    //最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode retLeft = lowestCommonAncestor(root.left,p,q);
        TreeNode retRight = lowestCommonAncestor(root.right,p,q);
        if(retLeft != null && retRight != null) {
            return root;
        }else if(retLeft != null) {
            return retLeft;
        }else{
            return retRight;
        }
    }

    public TreeNode lowestCommonAncestor2(TreeNode root,
                                          TreeNode p, TreeNode q) {
        if(root == null || p == null || q == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root,p,stack1);

        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,q,stack2);

        int size1 = stack1.size();
        int size2 = stack2.size();

        if(size1 > size2) {
            int tmp = size1-size2;
            while (tmp != 0) {
                stack1.pop();
                tmp--;
            }
        }else {
            int tmp = size2-size1;
            while (tmp != 0) {
                stack2.pop();
                tmp--;
            }
        }
        //两个栈当中 元素的个数是一样的
        while (!stack1.empty() && !stack2.empty())  {
            if(stack1.peek() == stack2.peek()) {
                return stack1.peek();
            }else {
                stack1.pop();
                stack2.pop();
            }
        }
        return null;//没有公共祖先
    }

    /**
     * 找到根节点到指定节点node之间路径上的所有节点，存储到stack当中
     * @param root
     * @param node
     * @param stack
     */
    private boolean getPath(TreeNode root, TreeNode node,
                            Stack<TreeNode> stack) {
        if(root == null || node == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean ret1 = getPath(root.left,node,stack);
        //不能判断false的问题，因为此时只能证明左边不存在
        if(ret1) {
            return true;
        }
        boolean ret2 = getPath(root.right,node,stack);
        if(ret2) {
            return true;
        }
        // 根节点不是  跟的左边没找到  根的右边没找到
        stack.pop();
        return false;
    }

    public TreeNode prev = null;
    public void ConvertChild(TreeNode root) {
        if(root == null) return;
        ConvertChild(root.left);
        //System.out.print(root.val+" ");
        root.left = prev;
        if(prev != null) {
            prev.right = root;
        }
        prev = root;
        ConvertChild(root.right);
    }

    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null) return null;

        ConvertChild(pRootOfTree);

        TreeNode head = pRootOfTree;
        while(head.left != null) {
            head = head.left;
        }
        return head;
    }

    /*public int preIndex = 0;
    private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend) {
        //没有了左树  或者 没有了右树
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode( preorder[preIndex]);
        //找到当前根节点 在中序遍历中的位置
        int rootIndex = findInorderIndex(inorder, preorder[preIndex],inbegin,inend);
        preIndex++;

        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);

        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);

        return root;

    }

    private int findInorderIndex(int[] inorder,int val,int inbegin,int inend) {
        for(int i = inbegin;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return buildTreeChild(preorder,inorder,0,inorder.length-1);

    }*/

/*
    public int postIndex = 0;

    private TreeNode buildTreeChild(int[] postorder,int[] inorder,int inbegin,int inend) {
        //没有了左树  或者 没有了右树
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode( postorder[postIndex]);
        //找到当前根节点 在中序遍历中的位置
        int rootIndex = findInorderIndex(inorder, postorder[postIndex],inbegin,inend);
        postIndex--;
        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);
        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);
        return root;
    }

    private int findInorderIndex(int[] inorder,int val,int inbegin,int inend) {
        for(int i = inbegin;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }*/

    public String tree2str(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        tree2strChild(root,sb);
        return sb.toString();
    }

    private void tree2strChild(TreeNode t,StringBuilder sb) {
        if(t == null) return ;
        sb.append(t.val);

        if(t.left != null) {
            sb.append("(");
            tree2strChild(t.left,sb);
            sb.append(")");
        }else {
            if(t.right == null) {
                return;
            }else{
               sb.append("()");
            }
        }

        if(t.right == null) {
            return;
        }else{
            sb.append("(");
            tree2strChild(t.right,sb);
            sb.append(")");
        }
    }

    public  void preorderTraversalNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            cur = top.right;
        }
    }


    public void inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }


    public void postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            //top.right 如果已经被访问了 也要弹出top所指向的节点
            if (top.right == null || top.right == prev) {
                stack.pop();
                System.out.print(top.val + " ");
                prev = top;
            } else {
                cur = top.right;
            }
        }
    }

}
